<template>
	<view class="userHome" :style="listHeightStyle">
		<!-- 基本信息 -->
		<view class="user">
			<view class="user-info">
				<view class="info-container">
					<image v-if="userStore.user.img_url" @click="openPreview" :src="userStore.user.img_url"
						mode="aspectFill">
					</image>
					<view
						style="height: 5rem; border-radius: 10%; background: #377fff; text-align: center; color: #ffffff; line-height: 5rem;"
						v-else>{{ this.userStore.user.worker_name }}</view>
				</view>
				<text class="worker-name">{{ this.userStore.user.worker_name }}</text>
			</view>
			<view class="admin-info">
				<!-- 总裁办-绿港本部园区-行政办公室 -->
				所在部门：
				{{ String(this.userStore.user.new_depart_name) === 'null' ? '暂无' : this.userStore.user.new_depart_name }}
			</view>
		</view>

		<AvatarPreview ref="avatar"></AvatarPreview>

		<!-- 功能 -->
		<view class="cell-group">
			<u-cell-group :border="false">
				<u-cell title="个人资料" :isLink="true" @click="handleJump('/pages/user/account')"></u-cell>
				<u-cell title="账号与安全" :isLink="true" @click="handleJump('/pages/user/safe')"></u-cell>
				<!-- <u-cell title="修改密码" :isLink="true" @click="editPWD()"></u-cell> -->
				<!-- <u-cell :border="false" title="基本设置" :isLink="true"></u-cell> -->
			</u-cell-group>
		</view>
		<!-- <view class="cell-group">
      <u-cell-group :border="false">
        <u-cell title="修改密码" :isLink="true" @click="editPWD()"></u-cell>
        <u-cell title="缓存更新" :isLink="true"></u-cell>
        <u-cell :border="false" title="软件更新" :isLink="true"></u-cell>
      </u-cell-group>
    </view> -->
		<view class="cell-group">
			<u-cell-group :border="false">
				<u-cell title="版本信息" :isLink="true" @click="handleJump('/pages/user/version')">
					<template #right-icon>
						<view style="font-size: 14px;" :style="{ color: versionStore.hasUpdate ? 'red' : '#606266' }">
							{{ versionLabel }}
						</view>
						<view style="font-size: 16px;color: #909399;">
							<up-icon name="arrow-right"></up-icon>
						</view>
					</template>
				</u-cell>
				<u-cell title="清除缓存" :isLink="true" :value="cacheSize" @click="handleClearCache()"></u-cell>
				<u-cell :border="false" title="常见问题" :isLink="true"></u-cell>
			</u-cell-group>
		</view>
		<view class="cell-group">
			<u-cell-group :border="false" class="cell-groupBtn">
				<u-cell @click="modalShow = true" title="退出登录" :isLink="true" :border="false"></u-cell>
			</u-cell-group>
		</view>

		<!-- 底部导航 -->
		<!-- <tabbar :value="4"></tabbar> -->

		<tui-modal :button="button" :show="modalShow" @click="modalClick" @cancel="modalShow = false"
			:content="content"></tui-modal>
	</view>
</template>

<script>
	import AvatarPreview from '@/components/avatar-preview/avatar-preview.vue';
	import tabbar from '@/components/home-tabbar/index.vue';
	import {
		useLoginStore,
		useUserStore,
		useStartTodoPolling,
		useSocketStore,
		useVersionStore
	} from "@/pinia-store/user.js";
	import {
		SysUser
	} from '@/utils/sql/user.js';
	import {
		mapStores
	} from 'pinia';


	export default {
		components: {
			tabbar,
			AvatarPreview
		},
		data() {
			return {
				content: '确认退出登录？',
				modalShow: false,
				button: [{
						text: "取消",
						type: "gray",
						plain: true
					},
					{
						text: "确定",
						type: "red",
						plain: false
					}
				],
				listHeight: 0, // 动态计算的高度
				listHeightStyle: {}, // 动态计算的样式
				topHeight: 0,
				appVersion: '',
				cacheSize: '0KB',
				isClearing: false,
			}
		},
		onLoad(option) {
			if (option.flag) { //说明修改密码回来的
				this.loginOut();
			}
			this.calculateListHeight();
			//获取版本信息
			this.getVersion();
			//获取缓存大小
			this.getCacheSize();
		},
		computed: {
			...mapStores(useUserStore, useLoginStore, useSocketStore, useVersionStore),
			departName() {
				const name = this.userStore.user.new_depart_name;
				return name === null || name === undefined ? '暂无' : name;
			},
			// 动态版本显示
			versionLabel() {
				return this.versionStore.hasUpdate ?
					"有新版本可更新" :
					this.appVersion;
			}
		},
		methods: {
			//退出账号删除订阅信息
			async removePushSubscription() {
				try {
					// 获取 Service Worker 注册
					const registration = await navigator.serviceWorker.ready;
					if (!registration) return;

					// 获取当前设备的订阅
					const subscription = await registration.pushManager.getSubscription();
					if (!subscription) return;

					// 调用服务端删除接口
					await fetch('https://push.mfarmers.com/api-push/subscription', {
						method: 'DELETE',
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify({
							endpoint: subscription.endpoint
						})
					});

					// 取消前端订阅
					await subscription.unsubscribe();
				} catch (err) {
					console.error('❌ 删除订阅失败:', err);
				}
			},
			calculateListHeight() {
				const windowHeight = window.innerHeight; // 视口高度
				const topHeight = this.topHeight; // 顶部安全高度
				const headerHeight = 50; // 顶部操作区域、搜索框等的高度

				// #ifdef APP-PLUS
				this.listHeightStyle = {
					height: `100vh`,
					overflowY: 'auto',
				};
				// #endif

				// #ifdef H5
				const listHeight = windowHeight - topHeight - headerHeight;
				this.listHeightStyle = {
					height: `${listHeight}px`,
					overflowY: 'auto',
				};
				// #endif
			},
			openPreview() {
				const that = this;
				uni.getSystemInfo({
					success(res) {
						that.$refs.avatar.open(res.windowWidth);
					}
				});
			},
			modalClick(e) {
				if (e.index == 1) {
					this.loginOut();
				} else {
					this.modalShow = false;
				}
			},
			loginOut() {
				const systemInfo = uni.getSystemInfoSync();
				const startTodoPolling = useStartTodoPolling();
				const socketStore = useSocketStore()
				const versionStore = useVersionStore()
				versionStore.reset()
				startTodoPolling.restart();

				// #ifdef APP-PLUS
				SysUser.deleteById(this.userStore.user.worker_id);
				// #endif

				// #ifdef H5  
				// 删除当前设备订阅
				if (typeof navigator !== 'undefined' && navigator.serviceWorker) {
					this.removePushSubscription().then(() => {}).catch(err => {
						console.error('删除订阅失败', err);
					});
				}
				// #endif
				uni.setStorageSync('localVersion', versionStore?.version || systemInfo?.appVersion);
				try {
					uni.clearStorageSync();
				} catch (error) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('user');
					uni.removeStorageSync('OAcurrentTab');
					uni.removeStorageSync('audioUnlocked');
					uni.removeStorageSync('_ws');
					uni.removeStorageSync('friend');
					uni.removeStorageSync('groupMsg');
					uni.removeStorageSync('nowDialogId');
				}
				// 用户信息写入缓存
				this.loginStore.logout();
				this.userStore.setUser(null);
				socketStore.handleClose()

				uni.reLaunch({
					url: "/pages/user/login"
				})
			},
			handleJump(url) {
				uni.navigateTo({
					url: url
				});
			},
			editPWD() {
				uni.navigateTo({
					url: '/pages/user/pwd?workerId=' + this.userStore.user.worker_id
				});
			},
			getVersion() {
				const systemInfo = uni.getSystemInfoSync();
				// #ifdef APP-PLUS
				this.appVersion = `版本 ${systemInfo.appWgtVersion}` // 原生APP的版本号（如Android/iOS）
				// #endif
				// #ifdef H5
				this.appVersion = `版本 ${systemInfo.appVersion}`; // H5环境的版本号
				// #endif
			},
			// 获取缓存大小
			async getCacheSize() {
				// H5和小程序平台
				// #ifdef H5 || MP-WEIXIN
				try {
					const info = uni.getStorageInfoSync();
					this.cacheSize = this.formatSize(info.currentSize * 1024);
				} catch (e) {
					console.error('获取缓存大小失败:', e);
					this.cacheSize = '0KB';
				}
				// #endif

				// APP平台
				// #ifdef APP-PLUS
				return new Promise(resolve => {
					plus.cache.calculate(size => {
						this.cacheSize = this.formatSize(size);
						resolve();
					});
				});
				// #endif
			},
			// 辅助方法：格式化缓存大小
			formatSize(bytes) {
				if (bytes < 1024) return bytes + 'B';
				if (bytes < 1048576) return (bytes / 1024).toFixed(2) + 'KB';
				return (bytes / 1048576).toFixed(2) + 'MB';
			},
			// 清除缓存
			async handleClearCache() {
				// 确认弹窗
				const {
					confirm
				} = await uni.showModal({
					title: '确认清理',
					content: '确定要清除所有缓存吗？此操作不可撤销！',
					confirmText: '立即清理',
					confirmColor: '#5677fc',
					cancelColor: "#555",
				});

				if (!confirm) return;

				uni.showLoading({
					title: '正在清理中...',
					mask: true
				});

				this.isClearing = true;

				try {
					// H5和小程序平台
					// #ifdef H5 || MP-WEIXIN
					uni.clearStorageSync();
					// #endif

					// APP平台
					// #ifdef APP-PLUS
					// Android平台
					if (plus.os.name === 'Android') {
						await this.clearAndroidCache();
					}
					// iOS平台
					else {
						await new Promise(resolve => plus.cache.clear(resolve));
					}
					// #endif

					uni.hideLoading();
					uni.showToast({
						title: '缓存清理成功',
						icon: 'success',
						duration: 2000
					});

					// 重置缓存大小显示
					this.cacheSize = '0KB';
					this.loginOut();
				} catch (error) {
					uni.hideLoading();
					console.error('清除缓存失败:', error);
					uni.showToast({
						title: '清除缓存失败',
						icon: 'error',
						duration: 2000
					});
				} finally {
					this.isClearing = false;
				}
			},

			// 清除Android缓存（APP平台专用）
			clearAndroidCache() {
				return new Promise(resolve => {
					const main = plus.android.runtimeMainActivity();
					const cacheDir = main.getCacheDir();
					const files = plus.android.invoke(cacheDir, "listFiles");

					let count = files.length;
					if (count === 0) return resolve();

					files.forEach(file => {
						const filePath = file.toString();
						plus.io.resolveLocalFileSystemURL(filePath, entry => {
							if (entry.isDirectory) {
								entry.removeRecursively(() => this.checkComplete(--count, resolve),
									e => this.checkComplete(--count, resolve));
							} else {
								entry.remove(() => this.checkComplete(--count, resolve),
									e => this.checkComplete(--count, resolve));
							}
						}, e => this.checkComplete(--count, resolve));
					});
				});
			},

			// 辅助方法：检查清理是否完成
			checkComplete(count, resolve) {
				if (count <= 0) {
					resolve();
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	// #ifdef APP-PLUS
	.userHome {
		box-sizing: border-box;
		background-color: #F3F4F5;
		padding: 280rpx 32rpx 0rpx 32rpx;

	}

	// #endif
	// #ifdef H5
	.userHome {
		box-sizing: border-box;
		background-color: #F3F4F5;
		padding: 184rpx 32rpx 0rpx 32rpx;

	}

	// #endif
	.user-info {
		position: absolute;
		top: -36rpx;
		left: 40rpx;
		display: flex;
		align-items: center;
		/* 垂直居中 */
	}



	.user {
		background-color: #fff;
		border-radius: 10rpx;
		position: relative;
		height: 96rpx;
		padding: 100rpx 40rpx 0 40rpx;

		.user-info {
			position: absolute;
			top: -36rpx;
			left: 40rpx;

			.info-container {
				width: 5rem;
				height: 5rem;
				border-radius: 10%;
				border: 0.125rem solid #fff;
				box-shadow: 0 0.125rem 0.375rem rgba(0, 0, 0, 0.1);
				position: relative;
				top: -1.5rem;
				background-color: #3D85FC;
				/* 蓝色背景 */
			}

			image {
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
				margin-right: 28rpx;
				/* 给头像与文字之间加点间距 */
			}

			.worker-name {
				font-size: 48rpx;
				font-weight: 500;

				/* 白色字体 */
			}

			text {
				font-size: 48rpx;
				font-weight: 500;
				margin-left: 28rpx;
			}
		}

		.admin-info {
			font-size: 28rpx;
			color: #aaa;
		}
	}

	.cell-group {
		margin-top: 30rpx;
		background-color: #fff;
		border-radius: 10rpx;
	}

	.cell-groupBtn {
		margin-bottom: 20rpx;
	}
</style>